define(['app', 'rtext!views/dialogs/templates/markdown-emoji.json'], function(app, txtEmoji) {
    app.controller('MarkdownEmojiController', function($sce, $showdown, $timeout, $uibModalInstance) {
        var self = this;
        self.emojis = {};

        self.init = function() {
            var emojis = {};
            _.forEach(JSON.parse(txtEmoji), function(emojiNames, category) {
                if (!emojis[category]) {
                    emojis[category] = [];
                }
                _.forEach(emojiNames, function(emojiName) {
                    var title = emojiName.replace(/_/g, ' ');
                    var emoji = ':' + emojiName + ':';
                    var html = $sce.trustAsHtml($showdown.makeHtml(emoji)
                            .replace(/<p>(.+)<\/p>/, '<a href="javascript:void(0)" title="' + title + '">$1</a>'));
                    emojis[category].push({
                        title: title,
                        html: html,
                        emoji: emoji
                    })
                });
            });
            self.emojis = emojis;

            $timeout(function() {
                resizeEmojiView();
                jQuery(window).on('resize', resizeEmojiView);
            });
        }

        self.select = function(emoji) {
            $uibModalInstance.close(emoji);
        }

        self.cancel = function() {
            $uibModalInstance.dismiss();
        }

        function resizeEmojiView() {
            if (jQuery(window).width() <= 768) {
                var marginLeft = (jQuery('.x-emoji-modal .tab-content').width() % 50 / 2) + 'px';
                jQuery('.x-emoji-modal .tab-content .x-emoji').each(function() {
                    jQuery(this).css('margin-left', marginLeft);
                });
            } else {
                jQuery('.x-emoji-modal .tab-content .x-emoji').each(function() {
                    jQuery(this).css('margin-left', '');
                });
            }
        };
    });
});
